<?php

/*
    This is one of the core files for nanacode
    Author : brant [X]
    last edited : 20111108
*/

class bluelight{

  var $domain;
  var $sql;
  
  function __construct()
  {
    $file = '../domain.yaml';
    if(!is_file($file)){
      $this->display('domain.yaml 不存在！');
    }
    $spyc = load('lib/spyc');
    $domain = Spyc::YAMLLoad($file);
    $ext = array();
    foreach($domain as $k => $d){
      
      if($k == 'ext'){
        foreach($d as $name => $label ){
          $ext[] = array('name'=>$name,'label'=>$label);
        }
        continue;
      }
      
      $d['name'] = $k;
      $fl = array();
      foreach($d['fields'] as $name => $label ){
        $fl[] = array('name'=>$name,'label'=>$label);
      }
      $dm[] = array('name'=>$k,'title'=>$d['title'],'fields'=>array_merge($fl,$ext));
    }
    $this->domain = $dm;
    //print_r($this->domain);
  }

  function index()
  {
    $ct ='
<script language="javascript">
 function sel(a,b){
  o=document.getElementsByName(a)
  for(i=0;i<o.length;i++)
  o[i].checked=b.checked
 }
</script>
<form method="POST" action="generate/">
<table><tr><th><input type="checkbox" onclick=sel("sid[]",this) >
</th><th>Name</th><th>Label</th><th></th></tr>';
    foreach($this->domain as $k => $d){
        $ct.= '<tr><td><input type="checkbox" name="sid[]" value="'.$k.'"/></td><td>'.$d['name'].'</td><td> '.$d['title'].'</td></tr>';
    }
    $ct.= '
    </table>
    <div><input type="checkbox" name="runSql" value="1"/> Run Sql</div>
    <div>path: <input type="text" name="path" value=""/> </div>
    <div><input type="submit" value="Generate!" ></div></form>';
    $this->display($ct);
  }

  function generate()
  {
    global $db;
    $this->path = $_POST['path']? $_POST['path']:'';
    if(!is_dir(APP.$this->path)) {
        mkdir(APP.$this->path,0777);
        mkdir(APP.$this->path.'v',0777);
        mkdir(APP.$this->path.'m',0777);
        mkdir(APP.$this->path.'c',0777);
    }
    
    $ct = '<ul>';
    if(is_array($_POST['sid'])) {
        foreach($_POST['sid'] as $p) {
            $ct.=$this->generateModule($this->domain[$p]);
        }
    }
    $ct.='</ul>';
    
    $this->display($ct.'<textarea style="height:200px;overflow:scroll;padding:10px;border:solid 1px #ccc;">'.$this->sql.'</textarea>');
    if($_POST['runSql'])$db->muti_query($this->sql);
  }


  /* generate a Modelue */

  function generateModule($m)
  {
    $this->generateM($m);
    $this->generateV($m);
    $this->generateC($m);
    $this->sql .= $this->generateMysql($m);
    return '<li>'.$m['name'].' was built successfully</li>';
  }

  function generateMysql($m)
  {
    $sql = '
DROP TABLE IF EXISTS `'.$m['name'].'`;
CREATE TABLE IF NOT EXISTS `'.$m['name'].'` (
  id INT NOT NULL auto_increment,';
    foreach($m['fields'] as $f){
        $sql .='
`'.$f['name'].'` varchar(255) COMMENT \''.$f['label'].'\',';
    }
    $sql .=
  'PRIMARY KEY(`id`)
);
';
    return $sql;
  }

  function generateM($m)
  {
    //print_r($m);
    foreach($m['fields'] as $f) {
      $fds[]=$f['name'];
    } 
    $file = '<?php
class '.$m['name'].'_m extends m {
  function __construct()
  {
    parent::__construct();
    $this->table = \''.$m['name'].'\';
    $this->fields = array(\''.implode('\',\'',$fds).'\');
  }
}';
    file_put_contents(APP.$this->path.'m/'.$m['name'].'.php',$file);
  }


/*******************************

  Generate Controllers

********************************/

  function generateC($m)
  {
    $object = $m['name'];
    $file = '<?php
class '.$object.' extends base{

  function __construct()
  {
    parent::__construct();
    $this->m = load(\'m/'.$object.'\');
  }

  function index()
  {
    $tot = $this->m->count();
    $psize = 30;
    $param[\'pagination\'] = pagination($tot , seg(3) , $psize ,\'/'.$object.'/index/\');
    $param[\'records\'] = $this->m->get("", seg(3), $psize);
    $this->display(\''.$object.'/list-table\',$param);
  }


  function view($id)
  {
    $param[\'r\'] = $this->m->get($id);
    $this->display(\''.$object.'/show\',$param);
  }


  function add()
  {
    $conf = array(';
    foreach($m['fields'] as $f) {
      $file.="'$f[name]'=>'required',";
    }
    $file.=');
    
    $err = validate($conf);
    if ( $err === TRUE) {
      $this->m->add();
      redirect(\'/'.$object.'/add/\',\'发布成功！\');
    }
    else {
      $param[\'val\'] = $_POST; 
      $param[\'err\'] = $err;
      $this->display(\''.$object.'/add\',$param);    
    }
  }    

  function edit($id)
  {
    $conf = array(';
    foreach($m['fields'] as $f) {
      $file.="'$f[name]'=>'required',";
    }
    $file.=');
    $err = validate($conf);
  	if ( $err === TRUE) {
      $this->m->update($id);
      redirect(\'/'.$object.'/\',\'修改成功！\');
    }
    else {
      $param[\'val\'] = array_merge($_POST,$this->m->get($id));
      $param[\'err\'] = $err;
      $this->display(\''.$object.'/add\',$param);    
    }
  }

  function del($id)
  {
    $this->m->del($id);
    redirect(\'/'.$object.'/\',\'删除成功！\');
  }
}';
    file_put_contents(APP.$this->path.'c/'.$m['name'].'.php',$file);
  }
  
  
/****************************

  generate views : add list view list-table
  
*****************************/    

  function generateV($m)
  {
    @mkdir(APP.$this->path.'v/'.$m['name']);
    
    // generate add.php view
    
    $file = '
<form method="POST" >
<table class="table-add table" cellspacing=0 >';
    foreach($m['fields'] as $f ){
      $file.= '
  <tr>
    <th>'.$f['label'].'</th>
    <td>
      <input class="text" name="'.$f['name'].'" value="<?=$val[\''.$f['name'].'\']?>" >
    </td><td class="error" ><?=$err[\''.$f['name'].'\']?></td></tr>';
    }
    $file.= '
    <tr>
      <th></th>
      <td><input type="submit" class="submit-button" value="确认提交" ></td>
    </tr>
  </table>
</form>';

    file_put_contents(APP.$this->path.'v/'.$m['name'].'/add.php',$file);
    
    //generate list.php view
    
    $file = '<ul class="'.$m['name'].'-list" >
<?
if(is_array($records )){
foreach ($records as $r ){ ?>
  <li>';
      foreach($m['fields'] as $f ){
        $file.= '
    <div>'.$f['label'].' <?=$r[\''.$f['name'].'\']?></div>';
      }
        
      $file.='
    <div>
      <a href="/'.$m['name'].'/view/<?=$r[\'id\']?>" >查看</a>
      <a href="/'.$m['name'].'/edit/<?=$r[\'id\']?>" >编辑</a> 
    </div>
  </li>
<?  }
}?>
</ul>
<?=$pagination?>';
    file_put_contents(APP.$this->path.'v/'.$m['name'].'/list.php',$file);

    //generate list-table.php view
    
    $file = '<table class="'.$m['name'].'-list-table table-list table" cellspacing=0 >
<?if(is_array($records )){?>
  <tr>';
      foreach($m['fields'] as $f ){
        $file.= '
    <th>'.$f['label'].'</th>';
      }
        
      $file.='
    <th>
      操作
    </th>
  </tr>
<?foreach ($records as $r ){?>
  <tr>';
      foreach($m['fields'] as $f ){
        $file.= '
    <td><?=$r[\''.$f['name'].'\']?></td>';
      }
        
      $file.='
    <td>
      <a href="/'.$m['name'].'/view/<?=$r[\'id\']?>" >查看</a>
      <a href="/'.$m['name'].'/edit/<?=$r[\'id\']?>" >编辑</a> 
    </td>
  </tr>
<?  }
}?>
</table>
<?=$pagination?>';
    file_put_contents(APP.$this->path.'v/'.$m['name'].'/list-table.php',$file);

    //generate view.php view
    
    $file = '
<table class="table-view  table" cellspacing=0 >';
    foreach($m['fields'] as $f ){
      $file .= '
  <tr>
    <th>'.$f['label'].'</th>
    <td><?=$r['.$f['name'].'] ?></td>
  </tr>';
    }      
    $file .= '
</table>
';
    file_put_contents(APP.$this->path.'v/'.$m['name'].'/show.php',$file);
  }
  
  function display($content)
  {
    echo '<html>
  <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><style>body{font:13px;}a{color:red;}th{background:#ccc;}table{float:left;border:solid 1px #ccc;margin-right:20px;}h1{color:#369;font-size:18px;}</style></head>
  <body>
    <h1>BlueLight</h1>
    <div><a href="/bluelight" >Home</a></div>
'.$content.'
  </body>
</html>';
    exit();
  }
}
